package com.graduate.examapp.request

import android.content.Context
import com.google.gson.*
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.jackson.JacksonConverterFactory
import java.lang.reflect.Type
import java.time.LocalDate
import java.util.concurrent.TimeUnit

/**
 * Author: etacao
 * Date: 2023/4/13 11:40
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * etacao 2023/4/13 1.0 首次创建
 */
object RetrofitRequest {
    var context: Context? = null

    private val client = OkHttpClient.Builder()
        .connectTimeout(1, TimeUnit.MINUTES)
        .readTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(2, TimeUnit.MINUTES)
        .addInterceptor(RequestInterceptor(context))
        .build()

    private val gson: Gson = GsonBuilder()
        .registerTypeAdapter(LocalDate::class.java, object : JsonDeserializer<LocalDate> {
            override fun deserialize(
                json: JsonElement?,
                typeOfT: Type?,
                context: JsonDeserializationContext?
            ): LocalDate {
                //日当前日期
                var localDate = LocalDate.now()
                json?.let {
                    val asString = it.asString
                    localDate = LocalDate.parse(asString)
                }
                return localDate
            }
        }).create()

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://192.168.118.97:8889")
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addConverterFactory(JacksonConverterFactory.create())
        .client(client)
        .build()

    private val serviceEndpoint = retrofit.create(ServiceEndpoint::class.java)

    fun getService(): ServiceEndpoint = serviceEndpoint
}